package com.shujia.flink.sink

import org.apache.flink.api.common.serialization.SimpleStringEncoder
import org.apache.flink.configuration.MemorySize
import org.apache.flink.connector.file.sink.FileSink
import org.apache.flink.core.fs.Path
import org.apache.flink.streaming.api.functions.sink.filesystem.rollingpolicies.DefaultRollingPolicy
import org.apache.flink.streaming.api.scala.{DataStream, StreamExecutionEnvironment}

import java.time.Duration

object Demo1FileSink {
  def main(args: Array[String]): Unit = {
    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment

    env.setParallelism(1)

    val linesDS: DataStream[String] = env.socketTextStream("master", 8888)

    //写入文件，老api
    //linesDS.writeAsText("flink/data/lines")

    val sink: FileSink[String] = FileSink
      //指定数据保存的路径和数据的格式
      .forRowFormat(new Path("flink/data/lines"), new SimpleStringEncoder[String]("UTF-8"))
      //指定滚动生成新文件的策略
      .withRollingPolicy(
        DefaultRollingPolicy.builder()
          //每个10毛产生一个新的文件
          .withRolloverInterval(Duration.ofSeconds(10))
          //10秒没有新的数据产生一个新的文件
          .withInactivityInterval(Duration.ofSeconds(10))
          //文件达到1M生成一个新的文件
          .withMaxPartSize(MemorySize.ofMebiBytes(1))
          .build())
      .build()

    //使用新版本的file sink
    linesDS.sinkTo(sink)

    env.execute()
  }

}
